// HTTP请求工具类
const BASE_URL = 'http://localhost:8080/api'

// 请求拦截器
const request = (options) => {
	return new Promise((resolve, reject) => {
		// 获取token
		const token = uni.getStorageSync('token')
		
		// 设置请求头
		const header = {
			'Content-Type': 'application/json'
		}
		
		if (token) {
			header['Authorization'] = `Bearer ${token}`
		}
		
		// 发起请求
		uni.request({
			url: options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: header,
			timeout: 10000, // 10秒超时
			success: (res) => {
				const { statusCode, data } = res
				
				if (statusCode === 200) {
					if (data.code === 200) {
						resolve(data)
					} else if (data.code === 401) {
						// token过期，清除登录信息并跳转到登录页
						console.log('收到401错误，清除登录状态')
						uni.removeStorageSync('token')
						uni.removeStorageSync('userInfo')
						
						// 避免重复跳转，检查当前页面
						const pages = getCurrentPages()
						const currentPage = pages[pages.length - 1]
						const currentRoute = currentPage ? currentPage.route : ''
						
						if (currentRoute !== 'pages/login/login') {
							uni.showToast({
								title: '登录已过期，请重新登录',
								icon: 'none'
							})
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}, 1500)
						}
						reject(new Error(data.message || '登录已过期'))
					} else {
						// 显示错误提示
						uni.showToast({
							title: data.message || '请求失败',
							icon: 'none'
						})
						reject(new Error(data.message || '请求失败'))
					}
				} else {
					reject(new Error(`HTTP ${statusCode}`))
				}
			},
			fail: (err) => {
				console.error('请求失败:', err)
				uni.showToast({
					title: '网络请求失败，请检查网络连接',
					icon: 'none'
				})
				reject(new Error('网络请求失败'))
			}
		})
	})
}

// 带重试机制的请求
const requestWithRetry = async (options, retries = 3, delay = 1000) => {
	for (let i = 0; i < retries; i++) {
		try {
			return await request(options)
		} catch (error) {
			if (i === retries - 1) throw error
			await new Promise(resolve => setTimeout(resolve, delay))
		}
	}
}

export { request, requestWithRetry }
export default request